package com.niit.syy.unitpricebyhouseaddr;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.text.DecimalFormat;

public class UnitPriceByHouseAddrReducer extends Reducer<Text, LongWritable, Text, Text> {
    private Text outv = new Text();
    private double unitPriceSum;// 累加所有单价（相同房屋地址）
    private int total;// 相同房屋地址的全部单价个数

    /**
     * reduce阶段核心业务逻辑（）
     *
     * @param key     驷马桥...
     * @param values  10200.....
     * @param context
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
        for (LongWritable value : values) {// 遍历驷马桥的所有单价
            unitPriceSum += value.get();// 10200.....遍历所有单价
            total++;
        }
        DecimalFormat df = new DecimalFormat("#.##");// 保留2位小数
        String formattedNumber = df.format(unitPriceSum / total);
        outv.set(formattedNumber + "元/㎡");
        context.write(key, outv);
    }
}
